package com.jerry.wschat.web.controller;

import com.jerry.wschat.model.Message;
import com.jerry.wschat.model.vo.MessageVO;
import com.jerry.wschat.model.vo.ReturnVO;
import com.jerry.wschat.model.vo.UserVO;
import com.jerry.wschat.service.MessageService;
import com.jerry.wschat.service.UserService;
import com.jerry.wschat.web.security.UserLogin;
import com.jerry.wschat.web.websocket.WebSocketUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author Jerry.Wu
 * @description:
 * @date 2018/9/26 15:59
 */
@Controller
@RequestMapping("/msg")
public class MessageController extends BaseController<Message, Integer>{

    @Autowired
    private UserService mUserService;

    @Autowired
    private MessageService mMessageService;

    @RequestMapping("/page")
    public ReturnVO page(Integer limit, Integer offset) {
        Page page = mMessageService.pageAll(limit, offset, "createTime", "DESC");
        return ReturnVO.OK(page);
    }

    @PostMapping("/send")
    public ReturnVO sendMessageAll(@RequestParam String content, HttpSession session) {
        UserLogin userLogin = getCurrentUser(session);
        Message message = new Message();
        message.setFromUserId(userLogin.getId());
        message.setContent(content);
        message.setCreateTime(new Date());
        mMessageService.save(message);

        MessageVO messageVO = new MessageVO();
        UserVO userVO = mUserService.loadUserVO(userLogin.getId());
        messageVO.setFromUserVO(userVO);
        WebSocketUtils.sendMessageAll(messageVO);
        return ReturnVO.OK();
    }

}
